import {Store} from 'iflux2';
import webApi from './webApi';
import {fromJS} from 'immutable';
import {message} from 'antd';

import ListActor from './actor/list-actor';
import SearchActor from './actor/search-actor';
import RefundActor from './actor/refund-actor';
import PaginationActor from 'actor/pagination';

import { PaginationType } from 'actor/pagination/type';
import {OrderListType, SearchActionType, RefundType} from './constant/action-type';


export default class AppStore extends Store {
    bindActor() {
        return [
            new ListActor,
            new SearchActor,
            new RefundActor,
            new PaginationActor,
        ]
    }

/***===========================SearchActor=============================================**/

    /**
     * 修改订单展示状态
     * @param filterKey
     */
    setOrderStatus = (filterKey)=>{
        this.dispatch(SearchActionType.SET_SEARCH_FILTER, filterKey);
    }
    //保存搜索字段内容
    changeSearchParams = (params) => {
        this.dispatch(SearchActionType.SET_SEARCH_PARAMS,fromJS(params));
    }
    setOrderType = (type)=>{
        this.dispatch(OrderListType.SET_TYPE, type);
    }


    /**
     * 设置分页信息
     * @param pagination
     */
    setPagination = (pagination)=>{
        this.dispatch(PaginationType.CHANGE_PAGE_PARAM, fromJS(pagination));
    }


    /**
     * 重置分页信息
     */
    resetPagination = ()=>{
        this.dispatch(PaginationType.RESET_PAGINATION_PARAM);
    }


/**==========================ListActor=============================================**/

    /**
     * 查询订单列表
     * @param params
     * @returns {Promise.<void>}
     */
    queryOrderList = async () => {
        const allState = this.state();
        const params = allState.get('search');
        const pagination = allState.get('pagination');
        //组装参数
        let postParams = Object.assign(params.toJS(), {
            pageNum: pagination.get('pageNum') - 1,
            pageSize: pagination.get('pageSize'),
            orderStatusEnum: allState.get('filterKey')
        });

        //查询订单列表
        try {
            const {orderPageList: {dataList, ...rest}, orderMapStatus, userLogos} = await webApi.queryOrderList(postParams);
            //页码加1
            rest.pageNum += 1;
            //dispatch数据
            this.dispatch(OrderListType.SET_LIST, {list: fromJS(dataList || []), orderMapStatus: fromJS(orderMapStatus || {})});
            this.dispatch(PaginationType.CHANGE_PAGE_PARAM, fromJS(rest));
            this.dispatch(OrderListType.SET_USER_LOGOS, fromJS(userLogos || {}))
        } catch(err) {//请求报错，暂无特殊处理
            message.error(err.message);
            return Promise.reject(err);
        }
    }


    /**
     * 查询物流公司
     * @returns {Promise.<*>}
     */
    queryExpressCompany = async ()=>{
        try {
            const companies = await webApi.queryShipCompanys();
            this.dispatch(OrderListType.SET_EXPRESS_COMPANY, fromJS(companies));
        } catch(err) {
            message.error(err.message);
            return Promise.reject(err);
        }
    }


    /**
     * 发货操作
     * @param params
     */
    deliveryOrder = async (params)=>{
        try {
            await webApi.deliveryOrder(params);
            message.success('发货成功');
            this.resetPagination();
            await this.queryOrderList();
        } catch (err) {
            message.error(err.message);
            return Promise.reject(err);
        }
    }


    refundBefore = async (tid = '')=>{
        try {
            const {applyRefundAmount, payAmount, tradeOrder, payTypeBOList} = await webApi.refundBefore(tid);
            this.dispatch(RefundType.SET_REFUND, {
                payAmount: fromJS(payAmount),
                tradeOrder: fromJS(tradeOrder),
                payTypeBOList: fromJS(payTypeBOList)
            });
        }
        catch (err) {
            message.error(err.message);
            return Promise.reject(err);
        }
    }

    refund = async (params = {})=>{
        try {
            await webApi.refund(params);
            message.success('申请退款成功');
            this.resetPagination();
            await this.queryOrderList();
        }
        catch (err) {
            message.error(err.message);
            return Promise.reject(err);
        }
    }

/**===============================订单相关操作=========================================**/


    /**
     * 复制订单
     * @param order
     * @returns {Promise.<*>}
     */
    copyTrade = async (order)=>{
        try {
            const {adminId, token} = await webApi.getToken(order.get('buyUsercode'));
            window.cloudshop_adminId = adminId;
            window.cloudshop_jwtToken = token;

            let skuList = order.get('itemOrders').filter(item=>item.get('isGift') == 0)
                .map(item=>{
                    return {
                        skuId: item.get('skuId'),
                        count: item.get('itemNumber')
                    }
                }).toArray();

            await webApi.cartConfirmCheck({skuList});
        } catch(err) {
            message.error(err.message);
            return Promise.reject(err);
        }
    }


    /**
     * 取消订单
     */
    cancelOrder = async (tid = '')=>{
        try {
            await webApi.cancelOrder(tid);
            message.success('订单取消成功');
            this.resetPagination();
            await this.queryOrderList();
        } catch(err) {
            message.error(err.message);
            return Promise.reject(err);
        }
    }



    /**
     * 开始导出任务
     * @param tidList
     * @returns {Promise.<void>}
     */
    startExportOrder = async (tidList)=>{
        try {
            const exportId = await webApi.startExportOrder({tidList})
            this.queryExport(exportId);
        } catch (err){
            message.error(err.message);
            return Promise.reject(err);
        }
    }


    /**
     * 查询导出进度，异步
     * @param exportId
     * @returns {Promise.<void>}
     */
    queryExport = async (exportId)=>{
        try {
            const id = await webApi.queryExport(exportId);
            if (!!id) {
                this.downloadOrder(id);
            } else {
                setTimeout(()=>{
                    this.queryExport(exportId);
                }, 2000)
            }
        } catch(err) {
            message.error(err.message);
            return Promise.reject(err);
        }
    }


    /**
     * 订单导出操作
     * @param exportId
     */
    downloadOrder = (exportId)=>{
        let tempform = document.createElement("form");
        tempform.action = `${$CONST_HOST['v_d2c_api']}/order/export/download/${exportId}`;
        tempform.method = 'post';
        tempform.style.display="none";
        let opt = document.createElement("input");
        opt.type = "submit";
        tempform.appendChild(opt);
        document.body.appendChild(tempform);
        tempform.submit();
        document.body.removeChild(tempform);
    }
}